<?php
/**
 * Created by PhpStrom
 * User: 郭碧云
 * Date: 2021/5/28 17:22
 * Desc:
 */

namespace App\Service;


use App\Facades\Site;
use App\Models\Admin\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoginService extends BaseService
{
    /**
     * 登陆用户验证
     */
    public function loginUser($params, Request $request) {
        unset($params["_token"]);
        unset($params["captcha"]);
        //锁定用户
        $lock = (new LoginService())->lockUser($params["name"]);
        if (!$lock) {
            return [
                "error" => 300000,
                "url" => "admin.login",
                "msg" => "密码错误次数超出上线，账号已锁定，请联系管理员找回密码"
            ];
        }
        //验证账号
        $check = $this->checkUser($params, $request);
        if (!$check) {
            return [
                "error" => 300001,
                "url" => "admin.login",
                "msg" => "账号/密码错误"
            ];
        }
        session(["guard" => $params["guard_name"]]);
        return [
            "error" => 0,
            "url" => "",
            "msg" => ""
        ];
    }

    /**
     * 锁定用户
     */
    private function lockUser($name) {
        //密码错误5次锁定
        $info = (new AdminUserService())->getErrorTime($name);
        //todo 需要补全设置互动
//        $set = (new SettingService("admin.Setting"))->first(["site_id"=>$info["site_id"],"name"=>"auth"]);
        if ($info["num"] >= 5) {
            return false;
        }
        return true;
    }

    /**
     * 验证账号是否正确
     */
    private function checkUser($params, Request $request) {
        //验证账号密码是否正确
        if (!Auth::guard($params["guard_name"])->attempt($params)) {
            //增加错误次数
            (new AdminUserService())->setLogin($request, 2, $params["name"], $params["guard_name"]);
            return false;
        }
        return true;
    }
}
